// 自有统计基本代码
;(function(win, doc, undefined) {

  var ttAnalysis = {},
    defaultParams = {},
    startTime = new Date().getTime(),
    isExpire = false;

  /**
   * 初始化
   */
  ttAnalysis.setup = function(params) {
    _extend(defaultParams, params);
  }

  /**
   * 事件发送函数，对外接口
   */
  ttAnalysis.send = function(type ,params) {
    var url = '//www.toutiao.com/api/article/user_log/?',
      log = [],
      logParams = {};

    _extend(logParams, defaultParams, params, {
      sid : _getSessionId(type === 'event'),
      type: type
    });

    if (type === 'close') {
      logParams.st = new Date().getTime() - startTime;
      if (isExpire) return;
    }

    for (k in logParams) {
      log.push(k + "=" + logParams[k]);
    }

    log.push('t=' + new Date().getTime());

    win['_ta_log_img_'] = new Image();
    win['_ta_log_img_'].src = url + log.join('&');
  }

  /**
   * 获取sessionId
   */
  function _getSessionId(update) {
    var sidTemp = _getCookie('__tasessionId');

    if (!sidTemp) {
      startTime = new Date().getTime();
      sidTemp = '' + _generateRandomAlphaNum(9) + new Date().getTime();
      _setCookie('__tasessionId', sidTemp, { expires: 30*60 });
      isExpire = true;
    } else if (sidTemp && update) {
      _setCookie('__tasessionId', sidTemp, { expires: 30*60 });
      isExpire = false;
    }

    return sidTemp;
  }

  /**
   * 生成随机函数
   */
  function _generateRandomAlphaNum(len) {
    var rdmString = "";
    for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
    return rdmString.substr(0, len);
  }

  /**
   * 浅拷贝
   */
  function _extend(obj) {
    var source, prop;

    for (var i = 1, length = arguments.length; i < length; i++) {
      source = arguments[i];
      for (prop in source) {
        if (Object.prototype.hasOwnProperty.call(source, prop)) {
          obj[prop] = source[prop];
        }
      }
    }
    return obj;
  }

  /**
   * cookie获取
   */
  function _getCookie(key) {
    var arr,reg = new RegExp("(^| )"+ key + "=([^;]*)(;|$)");
    if(arr = doc.cookie.match(reg)) return unescape(arr[2]);
    else return null;
  }

  /**
   * 秒为单位的过期时间设置
   */
  function _setCookie(key, value, params) {
    var expireTime,
      options = {
        path: '/'
      };

    _extend(options, params);

    if (options.expires) {
      expireTime = new Date();
      expireTime.setTime(expireTime.getTime() + params.expires*1000);
    }

    doc.cookie = [
      key, '=', escape(value),
      options.expires ? '; expires=' + expireTime.toUTCString() : '',
      options.path    ? '; path=' + options.path : '',
      options.domain  ? '; domain=' + options.domain : '',
      options.secure  ? '; secure' : ''
    ].join('');
  }

  // 浏览器关闭时发���
  win.onbeforeunload = function (e) {
    ttAnalysis.send('close', {});
  };

  win.ttAnalysis = ttAnalysis;

})(window, document, undefined);



//////////////////
// WEBPACK FOOTER
// ./static/lib/ttAnalysis.js
// module id = 460
// module chunks = 4
